/**
 * 
 */
package com.guohong.redis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author mao_g
 *
 */
@Configuration
public class JedisPoolFactory {
	@Value("${redisHost}")
	private String redisHost;
	@Value("${redisPort}")
	private int redisPort;
	@Value("${timeout}")
	private int timeout;
	@Value("${redisPassword}")
	private String redisPassword;
	@Value("${maxTotal}")
	private int maxTotal; // 资源池中最大连接数
	@Value("${maxIdle}")
	private int maxIdle; // 资源池允许的最大空闲连接数
	@Value("${minIdle}")
	private int minIdle; // 资源池确保的最少空闲连接数

	@Bean
	public JedisPoolConfig jedisPoolConfig() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxTotal(maxTotal);
		jedisPoolConfig.setMaxIdle(maxIdle);
		jedisPoolConfig.setMinIdle(minIdle);
		
		return jedisPoolConfig;
	}

	@Bean
	public JedisPool getJedisPool() {
		JedisPoolConfig jedisPoolConfig = jedisPoolConfig();
		JedisPool jedisPool = null;

		if (StringUtils.isNotBlank(redisPassword)) {
			// 既是连接超时又是读写超时
			jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, timeout, redisPassword);
		} else {
			// 既是连接超时又是读写超时
			jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, timeout, null);
		}

		return jedisPool;
	}
}
